<?php


namespace app\common\model;


use app\common\lib\exception\ApiException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use XznsTools\cache\CacheManage;

class UserPush extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_push';

    protected $cacheModel = 'user.push_regid';

    /**
     * 推送绑定
     * @param array $data
     * @param int $uid
     * @param int $type
     * @param int $notice_status
     * @throws ApiException
     * @throws \Exception
     */
    public function pushBind(array $data, int $uid, int $notice_type = 0, int $notice_status = 0)
    {
        $userPushData = $this->getUserRegid($uid);
        if (isset($data['device_token']) && $data['device_token'])
        {   // v14新接口 ios增加 device_token
            if (!empty($userPushData) && isset($userPushData['regid']) && $userPushData['regid'] === $data['regid'] && isset($userPushData['only_code'], $userPushData['status']) && $userPushData['only_code'] === $data['only_code'] && $userPushData['status'] === $data['status'] && $userPushData['version'] === $data['version'] && isset($userPushData['device_token'], $data['device_token']) && $userPushData['device_token'] === $data['device_token'])
            {
                return;
            }
        } else if (isset($data['only_code']) && $data['only_code'])
        {   // v14新接口
            if (!empty($userPushData) && isset($userPushData['regid']) && $userPushData['regid'] === $data['regid'] && isset($userPushData['only_code'], $userPushData['status']) && $userPushData['only_code'] === $data['only_code'] && $userPushData['status'] === $data['status'] && $userPushData['version'] === $data['version'])
            {
                return;
            }
        } elseif (isset($data['regid']) && $data['regid'])
        {   //v9 旧接口
            if (!empty($userPushData) && $userPushData['regid'] === $data['regid'])
            {
                return;
            }
        } else
        {  //v15 通知状态修改
            if ($userPushData)
            {
                if ($notice_type === 3)
                {
                    if ($notice_status === $userPushData['birth_status'])
                    {
                        return;
                    }
                }
            } else
            {
                return;
            }
        }
        try
        {
            if ($userPushData)
            {
                $this->where('id', $userPushData['id'])->update($data);
            } else
            {
                $data['uid'] = $uid;
                self::create($data);
            }
        }
        catch (\Exception $e)
        {
//            \think\Log::write('推送绑定失败:' . $e->getMessage(), 'error', true);
            throw new ApiException('推送绑定失败', 200, config('code.error'));
        }

        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
    }

    /**
     * 获取用户推送设备ID
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUserRegid(int $uid): array
    {
        $userPushData = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where('uid', $uid)->findOrFail()->toArray();
            }// model data Not Found
            catch (ModelNotFoundException $e)
            {
                $data = [];
            }// table data not Found
            catch (DataNotFoundException $e)
            {
                $data = [];
            }
            catch (Exception $e)
            {
                \think\Log::write('获取用户推送设备ID失败，UserPush->getUserRegid()：' . $e->getMessage(), 'error');
                $data = [];
            }

            return $data ?: [''];
        });

        $userPushData = array_filter($userPushData);
        if ($userPushData && (!isset($userPushData['only_code'], $userPushData['status'], $userPushData['fortune_status'], $userPushData['astro_status'], $userPushData['birth_status'])))
        {
            $userPushData = $this->where(['uid' => $uid])->findOrFail()->toArray();
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        }

        return $userPushData;
    }

    /**
     * 获取用户 是否允许回复我的状态 true 允许 false 不允许
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function getUserReplyStatus(int $uid): bool
    {
        $pushInfo = $this->getUserRegid($uid);

        $replySrarts = (int)($pushInfo['reply_status'] ?? 1); // 1开启 2关闭 0默认开启

        return $replySrarts !== 2; // 不等于关闭 则为开启
    }
}
